//=============================================================================
// System  : MatchKit
// File    : ExclusivePattern.cs
// Author  : Fabio Bussu  (matchkit@fabiobussu.it)
// Updated : 04/16/2013
// Note    : Copyright 2013, Fabio Bussu, All rights reserved
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code.  It can also be found
// at the project website: http://matchkit.codeplex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version     Date     Who  Comments
// ============================================================================
// 1.0.0.0  04/16/2013   FB  First draft
//=============================================================================
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;

namespace MatchKit.Patterns
{
	/// <summary>
	/// Provides the logic to match one of a set of patterns.
	/// </summary>
	/// <threadsafety static="true" instance="false" />
	/// <serialization binary="true" contract="true" />
	/// <conceptualLink target="cb485773-b793-4cc4-acc4-3688cdb226b6" />
	/// <conceptualLink target="0a06b2a9-5f58-409a-ba62-639cfd77bca7" />
	#if DC
	[DataContract]
	#endif
	#if SZ
	[Serializable]
	#endif
	public sealed class ExclusivePattern : BasePattern
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="T:MatchKit.Patterns.ExclusivePattern"/> class. 
		/// </summary>
		/// <param name="items">Set of pattern to search for. See <see cref="P:MatchKit.Patterns.ExclusivePattern.Items"/>.</param>
		public ExclusivePattern(params IPattern[] items)
		{
			Items = items;
		}

		/// <inheritdoc />
		public override IEnumerable<IPattern> Children
		{
			get { return _items; }
		}

		/// <inheritdoc />
		public override bool HasChildren
		{
			get { return true; }
		}

		private IPattern[] _items;
		/// <summary>
		/// Gets or sets the set of patterns to search for.
		/// </summary>
		/// <serialization member="true" />
		#if DC
		[DataMember]
		#endif
		public IPattern[] Items
		{
			get { return _items; }
			set
			{
				if (value == null)
					throw new ArgumentNullException("value", "Items cannot be null");
				if (value.Length == 0)
					throw new ArgumentException("Items must contains at least one element", "value");
				if (LinqUtils.Any(value, i => i == null))
					throw new ArgumentException("Items cannot contains null elements", "value");
				_items = value;
			}
		}

		/// <inheritdoc />
		protected override Match OnMatch(MatchContext context)
		{
			#region tracer
			var tracer = context.Tracer;
			int tryNo = 0;
			#endregion

			foreach (var item in _items)
			{
				if (item == null)
					throw new MatchKitException(29, "Exclusive pattern cannot contains null children elements");

				#region tracer
				if (tracer != null)
				{
					IMatchTracerExtensions.BeginMatch(tracer, context, item, "Begin Try #{0} : {1}", ++tryNo, item.HelpString);
				}
				#endregion

				var branch = context.Branch();
				var m = item.Match(branch);

				#region tracer
				if (tracer != null)
				{
					IMatchTracerExtensions.MatchComplete(tracer, context, m, "End with Try #{0}", tryNo);
				}
				#endregion

				if (m.Success)
				{
					context.Commit(branch);
					return Success(context, m.Value, m);
				}
			}

			return Error(context);
		}

		/// <inheritdoc />
		public override string HelpString
		{
			get
			{
				var sb = new StringBuilder(255);
				foreach (var item in _items)
				{
					if (sb.Length != 0)
						sb.Append(" || ");
					sb.Append(item.HelpString);
				}
				return "One of (" + sb + ")";
			}
		}
	}
}
